package com.baijiayun.liveuibase.base;

import android.graphics.drawable.Drawable;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import android.util.SparseArray;
import android.view.View;
import android.widget.TextView;

import io.reactivex.Observable;
import kotlin.Unit;

/**
 * 缓存引用，减少findViewById次数
 * Created by Shubo on 2017/3/15.
 */

public class QueryPlus extends Query {

    private SparseArray<View> viewRefCache;

    private QueryPlus(View contentView) {
        super(contentView);
        viewRefCache = new SparseArray<>();
    }

    public static QueryPlus with(View contentView) {
        return new QueryPlus(contentView);
    }

    @Override
    public QueryPlus id(int id) {
        View cachedView = viewRefCache.get(id);
        if (cachedView != null) {
            view = cachedView;
        } else {
            super.id(id);
            viewRefCache.put(id, super.view());
        }
        return this;
    }

    public Observable<Unit> clicks() {
        if (view == null) {
            throw new NullPointerException("view == null");
        }
        return RxClickKt.clicks(view);
    }

    public QueryPlus background(@ColorInt int color) {
        view.setBackgroundColor(color);
        return this;
    }

    public QueryPlus background(Drawable drawable) {
        view.setBackground(drawable);
        return this;
    }

    public QueryPlus setTextColor(@ColorInt int colorId) {
        if (view != null && view instanceof TextView && contentView().getContext() != null) {
            ((TextView) view).setTextColor(colorId);
        }
        return this;
    }

    public QueryPlus textColor(@ColorRes int resId) {
        if (view != null && view instanceof TextView && contentView().getContext() != null) {
            ((TextView) view).setTextColor(ContextCompat.getColor(contentView().getContext(),resId));
        }
        return this;
    }

    @Override
    public QueryPlus text(CharSequence text) {
        super.text(text);
        return this;
    }

    @Override
    public QueryPlus text(@StringRes int resId) {
        if (view != null && view instanceof TextView && contentView().getContext() != null) {
            ((TextView) view).setText(contentView().getContext().getString(resId));
        }
        return this;
    }

    public QueryPlus backgroundDrawable(Drawable drawable) {
        ViewCompat.setBackground(view, drawable);
        return this;
    }

    public void clearRefCache() {
        viewRefCache.clear();
    }
}
